﻿using BroadGoalComponents.BGControls.Toast;
using BroadGoalComponents.Dialogs;
using Custom.Controls;
using Custom.Framework;
using Custom.Model.Entity;
using Custom.Service.Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Custom.Config
{
    public partial class frmBakupConfig : PopupFormWithCover
    {
        private SysConfigRepository configDAL = new SysConfigRepository();

        public frmBakupConfig()
        {
            InitializeComponent();

            DragWindow drag = new DragWindow();
            drag.BindEvent(this, this.panel1);
        }

        private void frmBakupConfig_Load(object sender, EventArgs e)
        {
            SysConfig config = this.configDAL.Get(w => w.code == "BackupConfig")?.FirstOrDefault();
            if (config == null)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, 1) + ":\\会员系统备份\\";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                this.bgSelectTextBox1.Text = path;

                config = new SysConfig()
                {
                    name = "数据备份",
                    code = "BackupConfig",
                    value = path
                };
                this.configDAL.Insert(config);
            }
            else
            {
                this.bgSelectTextBox1.Text = config.value;
            }
        }

        private void bgSelectTextBox1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "请选择备份路径";
            folderBrowserDialog.ShowNewFolderButton = true;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                this.bgSelectTextBox1.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SysConfig config = this.configDAL.Get(w => w.code == "BackupConfig")?.FirstOrDefault();
                if (config == null)
                {
                    config = new SysConfig()
                    {
                        name = "数据备份",
                        code = "BackupConfig",
                        value = this.bgSelectTextBox1.Text
                    };
                    this.configDAL.Insert(config);
                }
                else
                {
                    config.value = this.bgSelectTextBox1.Text;
                    this.configDAL.Update(config);
                }
                BGToast.Show("保存成功");
                this.Close();
            }
            catch (Exception ex)
            {
                WarningDialog.Show("保存失败。" + ex.Message);
            }
        }
    }
}
